export default function (el: HTMLElement, p: any) {
    function removeClass(classval: string, dom: HTMLElement) {
        if (dom?.classList?.contains(classval)) {
            dom.classList.remove(classval);
        }
    }
    function addClass(classval: string, dom: HTMLElement) {
        if (!dom?.classList?.contains(classval)) {
            dom.classList.add(classval);
        }
    }
    function setTouchNone(el: any) {
        addClass('touch-none', el);
    }
    function setTouchAuto(el: any) {
        removeClass('touch-none', el);
    }
    function eStop(e: any) {
        const _e: any = window.event || e;
        _e?.preventDefault();
        _e?.stopPropagation();
        return true;
    }
    function eStopTouch(e: any) {
        const _e: any = window.event || e;
        if (_e.cancelable) {
            _e?.preventDefault();
            _e?.stopPropagation();
        }
    }

    function fnPThrottle(fn: any) {
        if (!p.timeout) {
            p.timeout = requestAnimationFrame(() => {
                fn();
                cancelAnimationFrame(p.timeout);
                p.timeout = null;
            });
        }
    }

    // touch事件处理
    function canTouch() {
        return 'ontouchstart' in window || navigator.maxTouchPoints;
    }
    function vtTouchInit(el: any) {
        if (canTouch() && p.touchstat !== 1) {
            el.addEventListener('touchstart', vtStart, true);
            p.touchstat = 1;
        }
    }
    function vtTouchDown(el: any) {
        if (canTouch() && p.touchstat !== 2) {
            // el.removeEventListener('touchmove', vtMove);
            // el.removeEventListener('touchend', vtEnd);
            el.addEventListener('touchmove', eStop);
            setTouchNone(el);
            p.touchstat = 2;
        }
    }
    function vtTouchUp(el: any) {
        if (canTouch() && p.touchstat !== 3) {
            el.removeEventListener('touchmove', eStop);
            setTouchAuto(el);
            p.touchstat = 3;
        }
    }
    function vtStart(e: any) {
        document.body.addEventListener('touchmove', vtMove);
        document.body.addEventListener('touchend', vtEnd);
        p.dragttm = Date.now();
    }
    function vtMove(e: any) {
        if (p.dragttm && Date.now() - p.dragttm < 1000) {
            p.dragtstat = 2;
        }
    }
    function vtEnd(e: any) {
        document.body.removeEventListener('touchmove', vtMove);
        document.body.removeEventListener('touchend', vtEnd);
        p.dragtstat = 0;
    }
    return {
        eStop,
        canTouch,
        eStopTouch,
        setTouchNone,
        setTouchAuto,
        fnPThrottle,
        vtTouchInit,
        vtTouchDown,
        vtTouchUp,
    };
}
